<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
<input type="file" value="sdgsdg" id="demo_input" />
<textarea id="result" rows=30 cols=300></textarea>
<img src="./1.jpg" alt="" style="width: 400px; height: 900px">
<canvas width="400" height="900" id="img_area"></canvas>

</body>

<script>
window.onload = function(){
	var input = document.getElementById("demo_input");
	var result= document.getElementById("result");
	var img_area = document.getElementById("img_area");
	if ( typeof(FileReader) === 'undefined' ){
		result.innerHTML = "抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！";
		input.setAttribute( 'disabled','disabled' );
	} else {
		input.addEventListener( 'change', readFile, false );}
}

function readFile() {
	var file = this.files[0];
	if (!/image\/\w+/.test(file.type)) {
		alert("请确保文件为图像类型");
		return false;
	}

	var reader = new FileReader();
	reader.readAsDataURL(file);
	console.log(file)
	reader.onload = function (e) {
		result.innerHTML = '<img src="' + this.result + '" alt=""/>';
		img_area.innerHTML = '<div class="sitetip">图片img标签展示：</div><img src="' + this.result + '" alt=""/>';
	}
}

// 获取图片
const img = document.querySelector('img');
//等待图像加载完毕
img.onload = function(){
	//获取图像的原始尺寸
	var naturalImgSize = [img.naturalWidth,img.naturalHeight];
	//设置新图像的尺寸（相对原始图像尺寸缩小一倍）
	//获取画布上下文
	const canvas = document.querySelector('canvas')
	const ctx = canvas.getContext("2d");
	// 绘制改变尺寸后的图像到画布上
	ctx.drawImage(img,0,0,naturalImgSize[0], naturalImgSize[1], 0, 0, naturalImgSize[0], naturalImgSize[1]);

	function compressImage(canvas,maxSize,quality,cb){
		canvas.toBlob(blob=>{
			if(blob.size > maxSize){
				compressImage(canvas,maxSize,quality-0.01,cb)
			}else{
				var file = new File([blob], "image.jpeg");
				var base64 = canvas.toDataURL("image/jpeg",quality)
				cb({
					file,
					base64
				})
			}
		},"image/jpeg", quality)
	}
	compressImage(canvas, 80*1024, 1, (opt)=>{
		console.log('aaa', opt);
	})
}


</script>

</html>
